import { defineConfig,loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import federation from "@originjs/vite-plugin-federation"
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js'; // 用于处理由 JS 注入的 CSS
// https://vite.dev/config/
// 主应用
export default defineConfig(({mode}) => {
  const env = loadEnv(mode, process.cwd());
  return {
    server: {
      port: 5000,
      host: '0.0.0.0',
      // proxy: {
      //   '/dist': {
      //       target: env.VITE_REMOTE_WEB1,
      //       changeOrigin: true,
      //         rewrite: (path) => path
      //     }
      // }
    },
    plugins: [
      vue(),
      federation({
        name: "hostMicro",
        filename: "hostMicroFrontendEntry.js",
        remotes: {
          // microFrontend: "http://localhost:5001/dist/assets/web1MicroFrontendEntry.js", // 使用子应用的
          microFrontend: `${env.VITE_REMOTE_WEB1}${env.VITE_REMOTE_WEB1_ENV === 'development' ? '/dist' : '' }/assets/web1MicroFrontendEntry.js`, // 使用子应用的
        },
        exposes: {
          "./Head": "./src/components/Head.vue",
          "./microFrontendHostUtil": "./src/utils/microFrontendHostUtil.ts",
        },
        shared: ["vue"]
      }),
      cssInjectedByJsPlugin({
        // 自定义过滤函数，指定要注入 CSS 代码的文件
        jsAssetsFilterFunction: (asset) => {
          if ('fileName' in asset) {
            // 使用正则表达式匹配文件名
            return /hostMicroFrontendEntry\.js$/.test(asset.fileName);
          }
          return false;
        }
      })
    ],
    build: {
      target: "esnext",
      minify: false,
      outDir: "dist",
      assetsDir: "assets",
      cssCodeSplit: false,
      // rollupOptions: {
      //   output: {
      //     // 确保CSS文件名与你的需求一致
      //     assetFileNames: 'assets/[name].[hash].[ext]'
      //   }
      // }
    }
  }
})
